package com.zut.edu.utils;

import android.content.Context;
import android.media.AudioManager;
import android.speech.tts.TextToSpeech;
import android.widget.Toast;

import java.util.Locale;

public class SystemTTSUtils {
    //创建自带语音对象
    public TextToSpeech textToSpeech = null;
    /**
     * 初始化TextToSpeech对象
     */
    public void initTTS(final Context context, final String text) {

        //实例化自带语音对象
        textToSpeech = new TextToSpeech(context, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == 0) {


                    AudioManager audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
                    audioManager.setSpeakerphoneOn(true);//使用扬声器外放，即使已经插入耳机

                    textToSpeech.setLanguage(Locale.SIMPLIFIED_CHINESE);
                    textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
                    textToSpeech.setPitch(1.5f);//方法用来控制音调
                    textToSpeech.setSpeechRate(1.5f);//用来控制语速

                    //判断是否支持下面两种语言
                    int result1 = textToSpeech.setLanguage(Locale.US);
                    int result2 = textToSpeech.setLanguage(Locale.
                            SIMPLIFIED_CHINESE);
                    boolean a = (result1 == TextToSpeech.LANG_MISSING_DATA || result1 == TextToSpeech.LANG_NOT_SUPPORTED);
                    boolean b = (result2 == TextToSpeech.LANG_MISSING_DATA || result2 == TextToSpeech.LANG_NOT_SUPPORTED);

                } else {
                    Toast.makeText(context, "数据丢失或不支持", Toast.LENGTH_SHORT).show();
                }

            }
        });
    }
}
